package com.capgemini.simpleappblanche.utils;

import java.lang.reflect.ParameterizedType;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author jcdorchies
 * TODO put comment in this class
 * @param <E>
 * @param <K>
 */
public abstract class AbstractDaoJpaBase<E, K> implements GenericDao<E, K> {

	protected final Logger logger = LoggerFactory.getLogger(getClass());
	
	protected Class<E> clazz;

	@PersistenceContext
	private EntityManager entityManager;
	
	public AbstractDaoJpaBase() {
		ParameterizedType genericSuperclass = (ParameterizedType) getClass()
				.getGenericSuperclass();
		this.clazz = (Class<E>) genericSuperclass.getActualTypeArguments()[0];
	}

	public E findById(K pK) {
		return entityManager.find(clazz, pK);
	}

	public E persist(E entity) {
		entityManager.persist(entity);
		
		return entity;
	}

	public E merge(final E entity) {
		return entityManager.merge(entity);
	}
	
	public void remove(E entity) {
		entityManager.remove(entity);
	}
	
	public List<E> findAll() {
		 final TypedQuery<E> query = entityManager.createQuery("from " + clazz.getName(), clazz);
		 return query.getResultList();
	}
	
	public E singleResultOrNull(final TypedQuery<E> query) {
		try {
			return query.getSingleResult();
		} catch (final javax.persistence.NoResultException e) {
			return null;
		}

	}
	
	public String getEntityName() {
		return clazz.getName();
	}
	
	public EntityManager getEntityManager() {
		return entityManager;
	}
	
}
